import modelExtend from 'dva-model-extend'
import * as empAchievementService from './services/empAchievement'
import * as departmentService from '../department/services/departments'
import {pageModel} from 'utils/model'
import * as employeeService from "../employee/services/employees"

const { query } = empAchievementService

export default modelExtend(pageModel, {
  namespace: 'empAchievement',
  state: {
    dimension: 'employee',  //维度筛选字段
    employees: [],
    departments: []
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/empAchievement') {
          const payload = location.query || { current: 1, size: 10 }
          dispatch({
            type: 'query',
            payload,
          })
          dispatch({
            type: "init"
          })
          dispatch({
            type: 'searchEmp',
            payload: {key: "any"},
          })
        }
      })
    },
  },
  effects: {
    * query({ payload = {} }, { call, put }) {
      console.log(payload)
      const response = yield call(query, payload)
      const { data } = response
      if (response && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data,
          },
        })
      }
    },

    * searchEmp ({payload = {}}, {call, put}) {
      const response = yield call(employeeService.searchEmp, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'updateState',
          payload: {
            employees: data,
          },
        })
      }
    },

    * init({ payload = {} }, { call, put }) {
      const deptResp = yield call(departmentService.query)

      yield put({
        type: 'updateState', payload: {
          departments: deptResp.data,
        },
      })
    },
  },

  reducers: {
    updateDimension(state, { payload }) {
      return { ...state, ...payload }
    }
  }
})
